package Aula17;

public class HashDic {
	
	private final int TAMANHO_INICIAL = 10; //Se for muito pequeno o algoritmo vai falhar.
	private String[] array;
	private int size;
	
	public HashDic(){
		array = new String[TAMANHO_INICIAL];
		size = 0;
	}
	
	private int hashCode(String str, int probe){
		int sum = 0;
		int length = str.length();
		for(int i = 0; i < length; i++){
			sum += str.charAt(i);
		}
		return (sum + probe) % array.length;
	}
	
	private void rehash(){
		String[] newArray = new String[array.length * 2];
		size = 0;
		for(int i = 0; i < array.length; i++){
			if(newArray[i] != null){
				add(array[i], newArray);
			}			 
		}
		array = newArray;
	}
	
	private boolean add(String str, String[] array){
		int code;
		int i = 0;
		while(true){
			code = hashCode(str, i);
			if(array[code] == null){
				size++;
				array[code] = str;
				return true;
			}
			if(array[code].equals(str)){
				return false;
			}
			i++;
		}
	}
	
	public boolean add(String str){
		if(size > 0.6 * array.length){
			rehash();
		}
		return add(str, array);
	}
	
	public boolean contains(String str){
		int i = 0;
		int code = hashCode(str, i);
		while(array[code] != null){
			if(array[code].equals(str)){
				return true;
			}
			i++;
			code = hashCode(str, i);
		}
		return false;
	}

}
